import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterapp900sui/controllers/businessDetailPageController.dart';
import 'package:flutterapp900sui/models/commonModels.dart';

import 'package:flutterapp900sui/views/businessListItemCell.dart';

import 'package:flutterapp900sui/models/listModelItems.dart';
import 'package:flutterapp900sui/views/filterMenuView.dart';

import 'package:flutterapp900sui/models/networking.dart';
import 'package:flutterapp900sui/models/networkApiList.dart';

class BusinessListPageWidget extends StatefulWidget {
  BusinessListPageWidget({Key key}) : super(key: key);

  @override
  _BusinessListPageWidgetState createState() => _BusinessListPageWidgetState();
}

class _BusinessListPageWidgetState extends State<BusinessListPageWidget> {

  CommonPageModel _pageModel = CommonPageModel();

  //  筛选条件
  List<ListCellItem> filterItems = [];

  //  筛选条件-区域
  List<ListCellItem> _filterRegionOptionItems = [];
  //  筛选条件-分类
  List<ListCellItem> _filterCategoryOptionItems = [];
  //  筛选条件-条件
  List<ListCellItem> _filterSortOptionItems = [];

  FilterMenuViewController menuViewController = FilterMenuViewController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    var item1 = ListCellItem("区域");
    item1.selectedHandleBlock = (){
      print('条件1被选中');
    };
    filterItems.add(item1);
    var item2 = ListCellItem("分类");
    item2.selectedHandleBlock = (){
      print('条件2被选中');
    };
    filterItems.add(item2);
    var item3 = ListCellItem("排序");
    item3.selectedHandleBlock = (){
      print('条件3被选中');
    };
    filterItems.add(item3);

    _downloadListData();

    _downloadFilterRegionAndDistrictData();
    _downloadFilterCategoryData();
    _downloadFilterSortData();
  }

  @override
  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(
        title: Text('附近商家'),
      ),
      body: Stack(
        children: [
          Container(
            margin: EdgeInsets.only(top: 44.0),
            child: RefreshIndicator(child: _listViewBuild(), onRefresh: _onRefresh)
          ),
          FilterMenuView(items: filterItems,menuViewController: this.menuViewController),
          FilterMenuPannelView(menuViewController: this.menuViewController,items: [
            FilterMenuPannelItem(itemWidget: FilterOptionView(type: FilterOptionType.double,optionItems: _filterRegionOptionItems,onSelectedBlock: (items){
              this.menuViewController.hide();
              print('选择的区域:${items.first.title}-${items.last.title}');

            },), itemHeight: 280),
            FilterMenuPannelItem(itemWidget: FilterOptionView(type: FilterOptionType.double,optionItems: _filterCategoryOptionItems,onSelectedBlock: (items){
              this.menuViewController.hide();
              },), itemHeight: 300),
            FilterMenuPannelItem(itemWidget: FilterOptionView(type: FilterOptionType.single,optionItems: _filterSortOptionItems,onSelectedBlock: (items){
              this.menuViewController.hide();
            },), itemHeight: _filterSortOptionItems.length * 55.0),
          ],)
        ],
      )
    );
  }

  //  创建listView组件
  Widget _listViewBuild(){
    return ListView.separated(itemBuilder: (BuildContext context,int index){
      return _getListViewCellBuild(index);
    }, separatorBuilder: (BuildContext context,int index){
      return Divider(color: Colors.grey[200]);
    }, itemCount: _pageModel.total > 0 ? _pageModel.listItems.length + 1 : 0);
  }

  //  创建listView的cell组件
  Widget _getListViewCellBuild(int index){
//  如果到了表尾
    if(index == _pageModel.listItems.length) {
      //  不足100条，则继续获取数据
      if(_pageModel.listItems.length < _pageModel.total){
        //  获取数据
        _downloadMoreListData();
        //  加载时显示loading
        return Container(
          padding: const EdgeInsets.all(16.0),
          alignment: Alignment.center,
          child: SizedBox(
            width: 24.0,
            height: 24.0,
            child: CircularProgressIndicator(strokeWidth: 2.0),
          ),
        );
      }
      else {
        //  已经加载了100条数据，不再获取数据
        return Container(
          alignment: Alignment.center,
          padding: EdgeInsets.all(16.0),
          child: Text('没有更多了',style: TextStyle(color: Colors.grey)),
        );
      }
    }
    //  显示单词列表项
    return BusinessListItemCell(handleBlock: (int selected){
      print("回调的参数为$index");
      Navigator.push(context, MaterialPageRoute(builder: (_){
        return new BusinessDetailPageWidget();
      }));
    },cellItem: _pageModel.listItems[index],);
  }

  //  单级筛选

  //  下拉刷新功能
  Future<Null> _onRefresh(){
    return Future.delayed(Duration(seconds: 2),(){
      _downloadListData();
    });
  }

  //  Private 方法
  //  加载数据资源
  void _downloadListData(){

    var parameters = {"pageSize":"20","page":"1"};
    Networking.get(RequestListApi.api_getShopList,parameters: parameters).then((value){
      Map itemJson = value['data'];
      _pageModel.loadingItems(itemJson, 1);
      setState(() {});
    });
  }

  void _downloadMoreListData(){

    var nextPage = _pageModel.page + 1;
    var parameters = {"pageSize":"20","page":"${nextPage}"};

    Networking.get(RequestListApi.api_getShopList,parameters: parameters).then((value){
      Map itemJson = value['data'];
      _pageModel.loadingItems(itemJson, nextPage);
      setState(() {});
    });
  }
  //
  void _downloadFilterRegionAndDistrictData(){
    var parameters = {"regionId":"321"};
    Networking.get(RequestListApi.api_filter_getRegionAndDistrict,parameters: parameters).then((value){
      _filterRegionOptionItems.clear();

      if(value['data'] is List){
        var tmpList = value['data'];

        var cellItem = ListCellItem('附近');
        _filterRegionOptionItems.add(cellItem);

        tmpList.forEach((element) {
          var cellItem = ListCellItem(element['RegionName']);
          cellItem.key = element['RegionId'].toString();
          _filterRegionOptionItems.add(cellItem);

          var subCellItem = ListCellItem('全部');
          cellItem.items.add(subCellItem);

          var tmpSubList = element['Sub'];
          tmpSubList.forEach((subElement){
            var subCellItem = ListCellItem(subElement['DistrictName']);
            subCellItem.key = subElement['DistrictId'].toString();
            cellItem.items.add(subCellItem);
          });
        });
      }
      setState(() {});
    });
  }

  void _downloadFilterCategoryData(){
    Networking.get(RequestListApi.api_filter_getIndustryAndIndus).then((value){
      if(value['data'] is Map){
        Map itemJson = value['data'];
        var tmpList = itemJson['List'];

        var cellItem = ListCellItem('全部');
        _filterCategoryOptionItems.add(cellItem);

        tmpList.forEach((element) {
          var cellItem = ListCellItem(element['IndustryName']);
          cellItem.key = element['IndustryId'].toString();
          _filterCategoryOptionItems.add(cellItem);

          var tmpSubList = element['Sub'];
          tmpSubList.forEach((subElement){
            var subCellItem = ListCellItem(subElement['Name']);
            subCellItem.key = subElement['IndusId'].toString();
            cellItem.items.add(subCellItem);
          });
        });
      }
      setState(() {});
    });
  }

  void _downloadFilterSortData(){
    Networking.get(RequestListApi.api_filter_getScreenBySort).then((value){
      _filterSortOptionItems.clear();

      if(value['data'] is List){
        var tmpList = value['data'];
        tmpList.forEach((element) {
          var cellItem = ListCellItem(element['Name']);
          cellItem.key = element['Id'].toString();
          _filterSortOptionItems.add(cellItem);
        });
      }
      setState(() {});
    });
  }
}